#include "vsprintf.h"

/* 将 printf 格式串转化成可直接输出的字符串，存储在 buf 中
 * 可以移植或自编，自编至少需要支持 %d （建议移植）
 */

//行吧，我用这个实现%d
int itoa(int n, char str[]) {
	int i = 0, remain = 0;
	if (n < 0) {
		str[i] = '-';
		i++;
		n = -n;
	}
	do {
		remain = n % 10;
		str[i] = remain + '0';
		i++;
		n /= 10;
	} while (n != 0);
	str[i] = '\0';
	int len = i;
	i--;
	for (int j = (str[0] == '-'); j < i; j++, i--) {
		char tmp = str[j];
		str[j] = str[i];
		str[i] = tmp;
	}
	return len;
}

int vsprintf(char *buf, const char *fmt, va_list args) {
	int i = 0;
	for (int j = 0, argindex = 0; j == 0 || fmt[j - 1] != 0;) {
		if (fmt[j] == '%') {  //实现%d
			j++;
			switch (fmt[j]) {
				case 'd': {
					int val = va_arg(args, int);
					i += itoa(val, buf + i);
					break;
				}
				case 'c': {
					buf[i] = va_arg(args, int);
					i++;
					break;
				}
			}
			j++;
		} else {
			buf[i] = fmt[j];
			i++;
			j++;
		}
	}
	return i;
}